package framework.crypto;

import lombok.SneakyThrows;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 一般性加密算法
 */
public interface GeneralCrypto {

    default boolean enable() {
        return true;
    }

    byte[] encrypt(byte[] data);

    @SneakyThrows
    default String encryptAsBase64(byte[] data) {
        byte[] encrypt = this.encrypt(data);
        return Base64.getEncoder().encodeToString(encrypt);
    }

    @SneakyThrows
    default String encryptAsBase64(String data) {
        byte[] encrypt = this.encrypt(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypt);
    }

    @SneakyThrows
    default String encrypt(String data) {
        byte[] encrypt = this.encrypt(data.getBytes(StandardCharsets.UTF_8));
        return new String(encrypt);
    }

    byte[] decrypt(byte[] data);

    @SneakyThrows
    default String decryptAsString(byte[] data) {
        byte[] decryptedBytes = this.decrypt(data);
        return new String(decryptedBytes, "UTF-8");
    }

    @SneakyThrows
    default String decryptAsString(String data) {
        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] decryptedBytes = this.decrypt(bytes);
        return new String(decryptedBytes, "UTF-8");
    }

    default byte[] decryptFromBase64(String base64) {
        byte[] bytes = Base64.getDecoder().decode(base64);
        byte[] decryptedBytes = this.decrypt(bytes);
        return decryptedBytes;
    }

    @SneakyThrows
    default String decryptFromBase64AsString(String base64) {
        byte[] bytes = Base64.getDecoder().decode(base64);
        byte[] decryptedBytes = this.decrypt(bytes);
        return new String(decryptedBytes, "UTF-8");
    }

    String getPublicKeyContent();

}
